package io.netty.client.IM;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class NettyServer {

    // 定义服务器端口号
    private int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void runServer() throws Exception {
        // 创建两个线程组 bossGroup 和 workerGroup，分别用于处理客户端的连接和读写事件
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建一个 ServerBootstrap 对象，并配置相关参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加 String 类型解码器和编码器，并设置字符集为 UTF-8
                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                            // 接收处理http请求，fullhttpRequest,fullHttpResponse
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(1024*64));

                            // websocket
                            pipeline.addLast(new WebSocketServerProtocolHandler("/"));
                            // 添加自定义的处理器，用于接收/返回消息
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            // 绑定端口号，启动服务器
            Channel ch = serverBootstrap.bind(port).sync().channel();
            System.out.println("Netty server started on port " + port);
            ch.closeFuture().sync();    // 阻塞，直到服务器关闭
        } finally {
            // 关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        NettyServer server = new NettyServer(8088);
        server.runServer();
    }
}
